package com.example.lenovo.asia5b.my.order.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.my.order.activity.BillListActivity;
import com.example.lenovo.asia5b.my.order.activity.ConfirmOrderActivity;
import com.example.lenovo.asia5b.my.order.activity.LogisticsActivity;
import com.example.lenovo.asia5b.my.order.activity.ParcelListActivity;
import com.example.lenovo.asia5b.my.order.activity.TheOrderActvity;
import com.example.lenovo.asia5b.my.order.bean.TheOrderBean;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DateUtils;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.ll_lay;

/**
 * Created by lenovo on 2017/6/21.
 */

public class TheOrderAdapter extends BaseAdapter implements ICallBack {

    private LayoutInflater mInflater;
    private  Context context;
    private List<TheOrderBean> theOrderBeanList;
    private LoadingDalog loadingDalog;
    public String path = System.currentTimeMillis()+"";
    private int width;

    public TheOrderAdapter(Context context) {
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        theOrderBeanList = new ArrayList<TheOrderBean>();
        loadingDalog = new LoadingDalog(context);
        width = DensityUtil.getScreenWidth(context)-120;
    }

    @Override
    public int getCount() {

        return theOrderBeanList.size();
    }

    @Override
    public Object getItem(int arg0) {
        return theOrderBeanList.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_the_order, null);
            holder.item_the_order_ll = (LinearLayout)convertView.findViewById(R.id.item_the_order_ll);
            holder.item_the_order_img = convertView.findViewById(R.id.item_the_order_img);
            holder.item_the_order_num = convertView.findViewById(R.id.item_the_order_num);
            holder.item_the_order_date = convertView.findViewById(R.id.item_the_order_date);
            holder.item_the_order_count = convertView.findViewById(R.id.item_the_order_count);
            holder.txt_logistics = (TextView)convertView.findViewById(R.id.txt_logistics);

            holder.item_the_order_payment = convertView.findViewById(R.id.item_the_order_payment);//付款
            holder.item_the_order_submit = convertView.findViewById(R.id.item_the_order_submit);//提交审核
            holder.btn_print_invoice = convertView.findViewById(R.id.btn_print_invoice);
            holder.txt_affirm_received = (TextView)convertView.findViewById(R.id.txt_affirm_received);
            holder.ll_lay = (LinearLayout)convertView.findViewById(ll_lay) ;
            holder.horizontalScrollView = (HorizontalScrollView)convertView.findViewById(R.id.horizontalScrollView) ;
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        TheOrderBean theOrderBean = theOrderBeanList.get(position);
        holder.item_the_order_num.setText("："+theOrderBean.order_sn);
//        DownloadPicture.loadNetwork(theOrderBean.thumb,holder.item_the_order_img);
        holder.item_the_order_date.setText( DateUtils.timedate(theOrderBean.add_time));

        holder.item_the_order_count.setText(theOrderBean.goods_num);
        holder.item_the_order_ll.setOnClickListener(new thrOrderClick(theOrderBean));
        //付款
        if (theOrderBean.order_status.equals("1") && theOrderBean.shipping_status.equals("0") && theOrderBean.pay_status.equals("0")) {
            holder.item_the_order_payment.setVisibility(View.VISIBLE);
        } else {
            holder.item_the_order_payment.setVisibility(View.GONE);
        }
        //查看物流
        holder.item_the_order_payment.setOnClickListener(new itemOrderPayment(theOrderBean));//付款
        if (TextUtils.isEmpty(theOrderBean.shipping_on)) {
            holder.txt_logistics.setVisibility(View.GONE);
        } else {
            holder.txt_logistics.setOnClickListener(new LogisticsOnClickListener(theOrderBean));
            holder.txt_logistics.setVisibility(View.VISIBLE);
        }
        //提交审核
        if (theOrderBean.order_status.equals("6") && theOrderBean.shipping_status.equals("0") && theOrderBean.pay_status.equals("0")){
            holder.item_the_order_submit.setVisibility(View.VISIBLE);
            holder.item_the_order_submit.setOnClickListener(new ReviewedClick(theOrderBean));
        } else {
            holder.item_the_order_submit.setVisibility(View.GONE);
        }
        //查看票据
        if (theOrderBean.isShowBill.equals("1")) {
            holder.btn_print_invoice.setOnClickListener(new DownloadClick(theOrderBean));
            holder.btn_print_invoice.setVisibility(View.VISIBLE);
        } else {
            holder.btn_print_invoice.setVisibility(View.GONE);
        }
        //确认收货
        if (theOrderBean.isshow .equals("1")&&theOrderBean.order_status.equals("1")){
            holder.txt_affirm_received.setVisibility(View.VISIBLE);
            holder.txt_affirm_received.setOnClickListener(new AffirmReceivedClcik(theOrderBean));
        } else {
            holder.txt_affirm_received.setVisibility(View.GONE);
        }

        try {
            holder.ll_lay.removeAllViews();
            JSONArray jsonArray = new JSONArray(theOrderBean.thumb);
            for (int i = 0; i < jsonArray.length(); i++) {
                View hotSaleView =  LayoutInflater.from(context).inflate(R.layout.item_hot_sale, null);
                ImageView image_commodity = (ImageView)hotSaleView.findViewById(R.id.image_commodity);
                TextView txt_name = (TextView)hotSaleView.findViewById(R.id.txt_name);
                image_commodity.setLayoutParams(new LinearLayout.LayoutParams(
                        width/5,
                        width/5));
                if (i != 0) {
                    hotSaleView.setPadding(DensityUtil.dip2px(context,5),0,0,0);
                }
                txt_name.setVisibility(View.GONE);
                DownloadPicture.loadNetwork(jsonArray.getString(i),image_commodity);
                image_commodity.setOnClickListener(new thrOrderClick(theOrderBean));
                holder.ll_lay.addView(hotSaleView,new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT,1));
            }
            if (jsonArray.length()<5) {
                holder.horizontalScrollView.setOnTouchListener(new HotOnTouchListener(theOrderBean));
            } else {
                holder.horizontalScrollView.setOnTouchListener(null);
            }
        } catch ( Exception e) {
        }
        return convertView;
    }

    private class ViewHolder {
        LinearLayout item_the_order_ll,ll_lay;
        ImageView item_the_order_img;
        TextView item_the_order_num;
        TextView item_the_order_date;
        TextView item_the_order_count;
        TextView item_the_order_payment;//付款
        TextView txt_logistics;
        TextView item_the_order_submit,btn_print_invoice,txt_affirm_received;
        HorizontalScrollView horizontalScrollView;
    }

    public void setList(List<TheOrderBean> theOrderBeanList){
        this.theOrderBeanList = theOrderBeanList;
    }

    public void clear() {
        theOrderBeanList.clear();
        notifyDataSetChanged();
    }

    class DownloadClick implements View.OnClickListener {
        private TheOrderBean theOrderBean;

        public DownloadClick(TheOrderBean theOrderBean){
            this.theOrderBean = theOrderBean;
        }
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, BillListActivity.class);
            intent.putExtra("order_sn",theOrderBean.order_sn);
            context.startActivity(intent);
        }
    }
    class thrOrderClick implements View.OnClickListener {

        private TheOrderBean theOrderBean;

        public thrOrderClick(TheOrderBean theOrderBean){
            this.theOrderBean = theOrderBean;
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,ParcelListActivity.class);
            intent.putExtra("order_id",theOrderBean.order_id);
            intent.putExtra("order_status",theOrderBean.order_status);
            intent.putExtra("mobile",theOrderBean.mobile);
            intent.putExtra("order_sn",theOrderBean.order_sn);
            ((Activity)context).startActivityForResult(intent,0);
        }
    }

    class itemOrderPayment implements View.OnClickListener{

        private TheOrderBean theOrderBean;

        public itemOrderPayment(TheOrderBean theOrderBean){
            this.theOrderBean = theOrderBean;
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,ConfirmOrderActivity.class);
            intent.putExtra("order_id",theOrderBean.order_id);
            intent.putExtra("is_specail",theOrderBean.is_specail);
            intent.putExtra("is_merge",theOrderBean.is_specail);
            ((Activity)context).startActivityForResult(intent,0);
        }
    }

    public class LogisticsOnClickListener implements View.OnClickListener {
        private TheOrderBean theOrderBean;

        public  LogisticsOnClickListener(TheOrderBean theOrderBean){
            this.theOrderBean = theOrderBean;
        }
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context,LogisticsActivity.class);
//            intent.putExtra("express_code","2017348010195751");
            intent.putExtra("express_code",theOrderBean.shipping_on);
            context.startActivity(intent);
        }
    }

    class ReviewedClick implements View.OnClickListener {
        TheOrderBean bean;
        public  ReviewedClick( TheOrderBean bean) {
            this.bean = bean;
        }

        @Override
        public void onClick(View view) {

            reviewedData(bean);
        }
    }

    class AffirmReceivedClcik implements View.OnClickListener {
        TheOrderBean bean;
        public  AffirmReceivedClcik( TheOrderBean bean) {
            this.bean = bean;
        }

        @Override
        public void onClick(View view) {
            affirmReceivedCData(bean);
        }
    }

    /**
     * 重新提交审核
     * @param bean
     */
    public void reviewedData( TheOrderBean bean ) {
        try {
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.REVIEWED;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"order_id"+bean.order_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",bean.order_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        }catch (Exception e) {

        }

    }

    /**
     * 确认 收货
     * @param bean
     */
    public void affirmReceivedCData(TheOrderBean bean) {
        try {
            loadingDalog.show();
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.AFFIRM_RECEIVED;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"order_id"+bean.order_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("order_id",bean.order_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        }catch (Exception e) {

        }

    }
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(context, context.getResources().getString(R.string.cg));
                            loadingDalog.show();
                            ((TheOrderActvity) context).page = 1;
                            ((TheOrderActvity) context).getPostAPI();
                        }
                        else if (state == 1) {
                            U.Toast(context,context.getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(context, context.getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(context, context.getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(context, context.getResources().getString(R.string.qxsb));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            U.Toast(context, context.getResources().getString(R.string.cg));
                            loadingDalog.show();
                            ((TheOrderActvity) context).page = 1;
                            ((TheOrderActvity) context).getPostAPI();
                        }
                        else if (state == 1) {
                            U.Toast(context,context.getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(context, context.getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(context, context.getResources().getString(R.string.wdl));
                        } else if (state == 4) {
                            U.Toast(context, context.getResources().getString(R.string.qxsb));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 判断文件是否存在
     * @param pathName
     * @return
     */
    public boolean fileIsExists(String pathName) {
        try {
            File f = new File(pathName);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }
        return true;

    }

    public Bitmap loadImageFromUrl(String url) throws Exception {
        final DefaultHttpClient client = new DefaultHttpClient();
        final HttpGet getRequest = new HttpGet(url);

        HttpResponse response = client.execute(getRequest);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            // System.out.println("Request URL failed, error code =" +
            // statusCode);
            Log.e("PicShow", "Request URL failed, error code =" + statusCode);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            Log.e("PicShow", "HttpEntity is null");
        }
        InputStream is = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            is = entity.getContent();
            byte[] buf = new byte[1024];
            int readBytes = -1;
            while ((readBytes = is.read(buf)) != -1) {
                baos.write(buf, 0, readBytes);
            }
        } finally {
            if (baos != null) {
                baos.close();
            }
            if (is != null) {
                is.close();
            }
        }
        byte[] imageArray = baos.toByteArray();
        return BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length);
    }


    class  HotOnTouchListener implements  View.OnTouchListener{
        private TheOrderBean theOrderBean;
        public  HotOnTouchListener(TheOrderBean theOrderBean) {
            this.theOrderBean = theOrderBean;
        }
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            //阻止手指离开时onTouch方法的继续执行
            if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                Intent intent = new Intent(context,ParcelListActivity.class);
                intent.putExtra("order_id",theOrderBean.order_id);
                intent.putExtra("order_status",theOrderBean.order_status);
                intent.putExtra("mobile",theOrderBean.mobile);
                intent.putExtra("order_sn",theOrderBean.order_sn);
                ((Activity)context).startActivityForResult(intent,0);
            }
            return false;
        }
    }

}